// 游戏状态
let gameState = {
  quote: "",
  currentQuoteIndex: 0,
  userInput: "",
  startTime: null,
  endTime: null,
  timer: 60,
  timerInterval: null,
  isGameActive: false
};

// DOM元素
const quoteDisplay = document.getElementById("quote-display");
const correctSpan = document.querySelector(".correct");
const currentSpan = document.querySelector(".current");
const untypedSpan = document.querySelector(".untyped");
const typingInput = document.getElementById("typing-input");
const wpmDisplay = document.getElementById("wpm");
const accuracyDisplay = document.getElementById("accuracy");
const timerDisplay = document.getElementById("timer");
const restartBtn = document.getElementById("restart-btn");
const quoteSetSelect = document.getElementById("quote-set");

// 初始化游戏
function initGame() {
  // 重置游戏状态
  gameState.currentQuoteIndex = 0;
  gameState.userInput = "";
  gameState.startTime = null;
  gameState.endTime = null;
  gameState.isGameActive = false;
  
  // 清除计时器
  if (gameState.timerInterval) {
    clearInterval(gameState.timerInterval);
    gameState.timerInterval = null;
  }
  
  // 重置UI
  gameState.timer = 60;
  timerDisplay.textContent = gameState.timer;
  wpmDisplay.textContent = "0";
  accuracyDisplay.textContent = "100";
  
  // 获取选中的名句集
  const selectedSet = quoteSetSelect.value;
  const quoteSet = quotes[selectedSet];
  
  // 随机选择一句名言
  const randomIndex = Math.floor(Math.random() * quoteSet.length);
  gameState.quote = quoteSet[randomIndex];
  
  // 显示名句
  renderQuote();
  
  // 清空输入框并聚焦
  typingInput.value = "";
  typingInput.focus();
}

// 渲染名句
function renderQuote() {
  if (gameState.currentQuoteIndex < gameState.quote.length) {
    const correctText = gameState.quote.substring(0, gameState.currentQuoteIndex);
    const currentChar = gameState.quote[gameState.currentQuoteIndex];
    const untypedText = gameState.quote.substring(gameState.currentQuoteIndex + 1);
    
    correctSpan.textContent = correctText;
    currentSpan.textContent = currentChar;
    untypedSpan.textContent = untypedText;
  } else {
    // 完成整句
    correctSpan.textContent = gameState.quote;
    currentSpan.textContent = "";
    untypedSpan.textContent = "";
    
    // 结束游戏
    endGame();
  }
}

// 处理用户输入
function handleInput(event) {
  if (!gameState.isGameActive && gameState.currentQuoteIndex === 0) {
    startGame();
  }
  
  if (!gameState.isGameActive) return;
  
  const inputValue = event.target.value;
  
  // 只比较当前输入的字符
  if (inputValue.length > gameState.userInput.length) {
    // 用户输入了新字符
    const newChar = inputValue[inputValue.length - 1];
    const expectedChar = gameState.quote[gameState.currentQuoteIndex];
    
    if (newChar === expectedChar) {
      // 正确输入
      gameState.currentQuoteIndex++;
      gameState.userInput = inputValue;
      
      // 为当前字符添加高亮动效
      currentSpan.classList.add("highlight");
      
      // 动画结束后移除类并更新显示
      setTimeout(() => {
        currentSpan.classList.remove("highlight");
        // 更新显示
        renderQuote();
        // 更新统计
        updateStats();
      }, 500);
    } else {
      // 错误输入，移除错误字符
      event.target.value = gameState.userInput;
    }
  } else if (inputValue.length < gameState.userInput.length) {
    // 用户删除了字符（简单处理，实际游戏中可能需要更复杂的逻辑）
    if (gameState.currentQuoteIndex > 0) {
      gameState.currentQuoteIndex--;
      gameState.userInput = inputValue;
      renderQuote();
      updateStats();
    }
  }
}

// 开始游戏
function startGame() {
  gameState.isGameActive = true;
  gameState.startTime = new Date();
  
  // 开始计时器
  gameState.timerInterval = setInterval(() => {
    gameState.timer--;
    timerDisplay.textContent = gameState.timer;
    
    if (gameState.timer <= 0) {
      endGame();
    }
  }, 1000);
}

// 结束游戏
function endGame() {
  gameState.isGameActive = false;
  gameState.endTime = new Date();
  
  // 清除计时器
  if (gameState.timerInterval) {
    clearInterval(gameState.timerInterval);
    gameState.timerInterval = null;
  }
  
  // 禁用输入
  typingInput.disabled = true;
  
  // 如果是时间到了，显示提示信息
  if (gameState.timer <= 0) {
    currentSpan.textContent = " (时间到!)";
  } else {
    // 如果是完成句子，显示完成信息
    currentSpan.textContent = " (完成!)";
  }
}

// 更新统计信息
function updateStats() {
  if (!gameState.startTime) return;
  
  const currentTime = new Date();
  const timeElapsed = (currentTime - gameState.startTime) / 1000 / 60; // 分钟
  const words = gameState.currentQuoteIndex / 5; // 假设每5个字符为一个单词
  
  // 计算WPM
  const wpm = timeElapsed > 0 ? Math.round(words / timeElapsed) : 0;
  wpmDisplay.textContent = wpm;
  
  // 计算准确率
  const totalInputs = gameState.userInput.length;
  const correctInputs = gameState.currentQuoteIndex;
  const accuracy = totalInputs > 0 ? Math.round((correctInputs / totalInputs) * 100) : 100;
  accuracyDisplay.textContent = accuracy;
}

// 重新开始游戏
function restartGame() {
  // 启用输入
  typingInput.disabled = false;
  
  // 初始化游戏
  initGame();
}

// 事件监听器
typingInput.addEventListener("input", handleInput);
restartBtn.addEventListener("click", restartGame);
quoteSetSelect.addEventListener("change", initGame);

// 页面加载完成后初始化游戏
document.addEventListener("DOMContentLoaded", () => {
  initGame();
});